package com.ebelter.scaleblesdk.util;


import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author 作 者：pan
 * @filename 文件名：EncryptUtil.java
 * @description 描 述：加密工具
 * @date 时 间：2017-8-31
 * @Copyright 版 权：倍泰源代码，版权归深圳市倍泰健康测量分析技术有限公司所有。
 */
public class EncryptUtilNew {
	
	public static final byte[] keyBytes = new byte[16];
	
	public static final byte[] ivBytes = new byte[16];
	
	static {
		String keys = "3d a2 78 4a fb 87 b1 2a 98 0f de 34 56 73 21 56";
		String ivs  = "4e f7 64 32 2f da 76 32 12 3d eb 87 90 fe a2 19";
		
		String[] keyArr = keys.split(" ");
		String[] ivArr = ivs.split(" ");
		
		for(int i = 0; i < 16; i++) {
			keyBytes[i] = (byte) Integer.parseInt(keyArr[i], 16);
			ivBytes[i] = (byte) Integer.parseInt(ivArr[i], 16);
		}
	}
	
	
	
	public static void setKeyBytes(byte[] bs) {
		
		for(int i = 0; i < bs.length; i++) {
			keyBytes[i] = bs[i];
			//ivBytes[i] = bs[i];
		}
	}
	
	/**
	 * 加密
	 * @param sSrc  源byte[]
	 * @return
	 * @throws Exception
	 */
	public static byte[] encrypt(byte[] sSrc) throws Exception {
//		Security.addProvider(new BouncyCastleProvider());
		Cipher cipher = Cipher.getInstance("AES/CTR/PKCS7Padding");
		byte[] raw = keyBytes;
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		IvParameterSpec iv = new IvParameterSpec(ivBytes);
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
		byte[] encrypted = cipher.doFinal(sSrc);
		return encrypted;
	}

	/**
	 * 数据解密
	 * @param sSrc
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] sSrc) throws Exception {
		try {
			byte[] raw = keyBytes;
//			Security.addProvider(new BouncyCastleProvider());
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES/CTR/PKCS7Padding");
			IvParameterSpec iv = new IvParameterSpec(ivBytes);
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			byte[] encrypted1 = sSrc;// new
			byte[] original = cipher.doFinal(encrypted1);
			return original;
		} catch (Exception ex) {
			return null;
		}
	}
}
